import { isDate, isObject } from "./utils";

function encode(url: string) {
  return encodeURIComponent(url)
  .replace(/%5B/g, '[')
  .replace(/%5D/g, ']')
  .replace(/%20/g, '+')
  .replace(/%2C/g, ',')
  .replace(/%2F/g, '/')
  .replace(/%3A/g, ':')
  .replace(/%3D/g, '=')
  .replace(/%3F/g, '?')
  .replace(/%40/g, '@')
  .replace(/%26/g, '&')
  .replace(/%23/g, '#');
}

export function buildRUL(url: string, params?: any) {
  // 如果params为空，则直接返回url
  if (!params) {
    return url;
  }

  const parts: string[] = []; // 存放结果

  Object.keys(params).forEach((key) => {
    const val = params[key];
    // 去除空值
    if (val === null || typeof val === "undefined") {
      return;
    }
    // 处理数组
    let values: any[] = [];
    if (Array.isArray(val)) {
      values = val;
      key += "[]";
    } else {
      values = [val];
    }
    values.forEach((val) => {
      if (isDate(val)) {
        val = val.toISOString(); // utc格式
      } else if (isObject(val)) {
        val = JSON.stringify(val);
      }
      parts.push(`${encode(key)}=${encode(val)}`);
    });
  });
  let serializedParams = parts.join("&"); // a=2&b=2
  if (serializedParams) {
    const markIndex = url.indexOf("#");
    if (markIndex !== -1) {
      url = url.slice(0, markIndex);
    }
    // 保留已有参数
    url += (url.indexOf("?") === -1 ? "?" : "&") + serializedParams;
  }

  return url;
}
